package com.fitz.core.context;

import com.fitz.core.filter.AbstractFilter;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author gousl01
 * @date 2021/3/15 17:22
 * @desc
 */
public class FilterRegistry {

    private FilterRegistry(){}

    public static final FilterRegistry INSTANCE = new FilterRegistry();

    public static FilterRegistry getInstance(){
        return INSTANCE;
    }

    public ConcurrentHashMap<String, AbstractFilter> filters = new ConcurrentHashMap<>();

    public final ConcurrentHashMap<String,List<AbstractFilter>> filtersByType = new ConcurrentHashMap<>();

    public void put(String key, AbstractFilter filter){
        filters.putIfAbsent(key,filter);
    }

    public AbstractFilter get(String key){
        return filters.get(key);
    }

    public void remove(String key){
        filters.remove(key);
    }

    public int size(){
        return filters.size();
    }

    public Collection<AbstractFilter> allFilters(){
        return filters.values();
    }

    /**
     * 获取不同类型的filters
     * @param filterType
     * @return
     */
    public List<AbstractFilter> getFiltersByType(String filterType){
        List<AbstractFilter> list = filtersByType.get(filterType);
        if(list != null){
            return list;
        }
        list = new ArrayList<>();
        //从所有的filters里面取出来放进去,懒加载,用的时候才取
        Collection<AbstractFilter> it = filters.values();
        for (AbstractFilter filter : it){
            if (filter.routeType().equals(filterType)){
                list.add(filter);
            }
        }
        Collections.sort(list);
        filtersByType.putIfAbsent(filterType,list);
        return list;
    }
}
